import axios from "axios";
import { showModal } from "@/utils/message";
import { storage } from "../../utils/storage";

const { NODE_ENV, VUE_APP_BASE_URL } = process.env
console.log('运行环境：', process.env, NODE_ENV, VUE_APP_BASE_URL);

export class Axios {
  constructor(options) {
    // init
    this.options = options || {};
    const defaultOptions = {
      baseURL: VUE_APP_BASE_URL,
    };
    this.options = Object.assign(defaultOptions, options);
    this.instance = axios.create(this.options);
    // 解决真机报错adapter is not a function,android与微信请求地址必须为http://或https://开头,且android不支持127.0.0.1与localhost
    // #ifdef MP-WEIXIN || APP-PLUS
    this.instance.defaults.adapter = function (config) {
      return new Promise((resolve, reject) => {
        const settle = require("axios/lib/core/settle");
        const buildURL = require("axios/lib/helpers/buildURL");
        let baseURL = config.baseURL || "";
        const urlLegal = config.url?.search(/http(s?):\/\//) !== -1;
        // url中存在http或https,将baseURL置空,此时加上baseURL去请求地址会出错
        urlLegal && (baseURL = "");
        const path = buildURL(config.url, config.params, config.paramsSerializer);
        const url = (baseURL + path).trim();
        // url不是http或https开头抛出异常
        if (url.search(/^http(s?):\/\//) === -1) {
          return Promise.reject({
            errMsg: "request address must start with http or https",
            url,
          });
        }
        uni.request({
          method: config.method.toUpperCase(),
          url,
          header: config.headers,
          data: config.data,
          dataType: config.dataType,
          responseType: config.responseType,
          sslVerify: config.sslVerify,
          timeout: config.timeout,
          complete: function complete(response) {
            response = {
              data: response.data,
              status: response.statusCode,
              errMsg: response.errMsg,
              header: response.header,
              config,
            };
            settle(resolve, reject, response);
          },
        });
      });
    };
    // #endif

    // axios请求拦截器
    this.instance.interceptors.request.use((config) => {
      let token = storage.get('token')
      if(token && config.url!='/member/login') {
        config.headers.Authorization = token
      }
      return config;
    });

    //axios响应拦截器
    this.instance.interceptors.response.use(
      // wx | app只会进这个拦截器,不管成功还是失败
      (response) => {
        try {
          const { config, data, status, errMsg } = response;
          console.log(status, 'status');
          if(status !== 200) {
            return Promise.resolve({ c: status, d: data || {},  m: '网络错误' })
          }
          return Promise.resolve(data)
        } catch (error) {
          return Promise.reject(error.message);
        }
      },
      (error) => {
        console.log('响应拦截器错误:  ', error)
        let message = error.message;
        if (message == "Network Error") {
          message = "后端接口连接异常";
        }
        else if (message.includes("timeout")) {
          message = "系统接口请求超时";
        }
        else if (message.includes("Request failed with status code")) {
          message = "系统接口" + message.substring(message.length - 3) + "异常";
        }
        showModal(message)
        return Promise.reject(error)
      },
    );
  }

  get(url, data, config) {
    return this.instance.get(url, {
      params: data,
      ...config,
    });
  }

  post(url, data, config) {
    return this.instance.post(url, data, {
      ...config,
    });
  }

  put(url, data, config) {
    return this.instance.put(url, data, {
      ...config,
    });
  }

  delete(url, data, config) {
    return this.instance.delete(url, {
      params: data,
      ...config,
    });
  }
}
